<template>
  <div class="banner" ref="bannerRef" @mousemove="mouseMove($event)">
    <div class="imgCon" v-for="(item, index) in imgList" :key="index">
      <img
        :src="item"
        :ref="
          (el) => {
            if (el) imgRefs[index] = el;
          }
        "
      />
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
  setup() {
    const imgList = ref([
      "/img/bilibili-autumn-1.png",
      "/img/bilibili-autumn-2.png",
      "/img/bilibili-autumn-3.png",
      "/img/bilibili-autumn-4.png",
      "/img/bilibili-autumn-5.png",
    ]);
    const imgRefs = ref<HTMLElement[]>([]);
    const bannerRef = ref<HTMLElement>();
    function mouseMove(e: any) {
      const dom = bannerRef.value;
      const percentage = e.clientX / dom!.clientWidth;

      let offset = 10;
      let blur = 10;
      imgRefs.value.forEach((img, index) => {
        offset *= 1.3; // 将位置按每一张图片乘大一点，达到越后面（越近）的图片位置越多
        blur *= Math.abs((index + 1) / 6 - percentage); // 模糊度计算，这个公式可以再优化
        img.style.setProperty("--offset", `${offset}px`); // 透过 CSS 变数形式设定到对应的图片
        img.style.setProperty("--blur", `${blur}px`); // 透过 CSS 变数形式设定到对应的图片
      });
    }
    return { bannerRef, mouseMove, imgList, imgRefs };
  },
});
</script>

<style lang="scss" scoped>
.banner {
  position: relative;
  height: 8rem;
  width: 100%;
  background: #eee;
  overflow: hidden;
  .imgCon {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    img {
      width: 110%;
      height: 100%;
      object-fit: cover;
      transform: translatex(var(--offset)); /* 获取位置设定值 */
      filter: blur(var(--blur)); /* 获取模糊度设定值 */
    }
  }
}
</style>
